// store/modules/user.js
import { Message } from 'element-ui'; // 导入 ElMessage
import {
  changeBasicMessage,
  getProjectExperience,
  getWorkExperience,
  updateProjectExperience,
  updateWorkExperience
} from "@/util/seeker_api/Person_api";
//求职者模块
import { getSeekerBasicInfo } from "@/api/login";
import { initWs } from '@/services/websocket';
import router from '@/router';

export default {
  // 启用命名空间，避免多个模块间命名冲突
  namespaced: true,
  // 状态定义
  state: {
    // 从本地存储获取token，如果不存在则为null
    token: localStorage.getItem('seekerToken') || null,
    // 从本地存储获取用户信息，如果不存在则为空对象
    userInfo: JSON.parse(localStorage.getItem('seekerUserInfo')) || {},
    projectExperience: JSON.parse(localStorage.getItem('seekerProjectExperience')) || [],
    workExperience: JSON.parse(localStorage.getItem('seekerWorkExperience')) || [],
    address: JSON.parse(localStorage.getItem('seekerAddress')) || '厦门市',
  },

  // 修改状态的方法
  mutations: {
    // 设置token并保存到本地存储
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem('seekerToken', token);
    },
    // 设置用户信息并保存到本地存储
    SET_USER_INFO(state, userInfo) {
      state.userInfo = { ...state.userInfo, ...userInfo };
      localStorage.setItem('seekerUserInfo', JSON.stringify(state.userInfo));
    },
    // 设置项目经验并保存到本地存储
    SET_PROJECT_EXPERIENCE(state, projectExperience) {
      state.projectExperience = projectExperience;
      localStorage.setItem('seekerProjectExperience', JSON.stringify(projectExperience));
    },
    // 设置工作经验并保存到本地存储 
    SET_WORK_EXPERIENCE(state, workExperience) {
      state.workExperience = workExperience;
      localStorage.setItem('seekerWorkExperience', JSON.stringify(workExperience));
    },
    // 设置地址并保存到本地存储
    SET_ADDRESS(state, address) {
      state.address = address;
      localStorage.setItem('seekerAddress', JSON.stringify(address));
    },
    // 清除所有状态和本地存储的数据
    CLEAR_STATE(state) {
      state.token = null;
      state.userInfo = {};
      state.userInfo.projectExperience = [];
      state.userInfo.workExperience = [];
      localStorage.removeItem('seekerToken');
      localStorage.removeItem('seekerUserInfo');
      localStorage.removeItem('seekerProjectExperience');
      localStorage.removeItem('seekerWorkExperience');
    }
  },
  // 异步操作方法
  actions: {
    //初始化状态
    async initAuth({ commit, state }) {
      const token = localStorage.getItem("seekerToken");
      if (token) {
        commit("SET_TOKEN", token);
        try {
          await dispatch('fetchSeekerInfo');

          // 新增：用户认证成功后初始化WebSocket
          initWs(token);
          dispatch('chat/initChatModule', null, { root: true });
        } catch (error) {
          // token无效，清除状态
          commit("CLEAR_STATE");
        }
      }
    },
    //获取用户信息
    async fetchSeekerInfo({ state, commit }) {
      if (!state.token) {
        return false;
      }

      try {
        // 调用API获取求职者信息
        const response = await getSeekerBasicInfo();

        if (response.data.code === 201 && response.data.data.userId) {
          commit('SET_USER_INFO', response.data.data);
          return true;
        } else {
          throw new Error(response.data.message || '用户信息获取失败');
        }
      } catch (error) {
        commit('CLEAR_STATE');
        return false;
      }
    },

    // 更新求职者基本信息的异步方法
    async updateUserInfo({ commit }, payload) {
      try {
        // 先更新本地状态
        commit('SET_USER_INFO', payload);

        // 再发送到后端（JSON格式）
        const response = await changeBasicMessage(JSON.stringify(payload));


        // 检查请求是否成功
        // if (response.code !== 201) {
        //   throw new Error(response.msg || '更新失败');
        // }

        // 
        const token = response.data.data;
        commit("SET_TOKEN", token);
        return response.data;
      } catch (error) {
        console.error('更新用户信息失败:', error);
        throw error;
      }
    },

    // 获取项目经验的异步方法
    async fetchProjectExperience({ state, commit }) {
      if (!state.token) throw new Error('Token不存在');
      try {
        // 调用API获取项目经验
        const response = await getProjectExperience();
        if (response.data.code !== 201 && response.data.data.userId) {
          throw new Error(response.msg || '获取信息失败');
        }
        // 更新项目经验
        commit('SET_PROJECT_EXPERIENCE', response.data.data);
        return response.data;
      } catch (error) {
        console.error('获取求职者项目经验失败:', error);
        // 发生错误时清除状态
        commit('CLEAR_STATE');
        throw error;
      }
    },

    // 更新项目经验的异步方法
    async renewProjectExperience({ commit }, projectExperience) {
      try {
        // 先更新本地状态
        const data = projectExperience;
        commit('SET_PROJECT_EXPERIENCE', data.projectExperience);

        const response = await updateProjectExperience(data.projectExperience);
        // 检查请求是否成功
        // if (response.code !== 201) {
        //   throw new Error(response.msg || '更新失败');
        // }
        const token = response.data.data;
        commit("SET_TOKEN", token);

        return response.data;
      } catch (error) {
        console.error('更新项目经验失败:', error);
        throw error;
      }
    },

    // 获取工作经验的异步方法
    async fetchWorkExperience({ state, commit }) {
      if (!state.token) throw new Error('Token不存在');
      try {
        // 调用API获取工作经验
        const response = await getWorkExperience();
        if (response.data.code !== 201 && response.data.data.userId) {
          throw new Error(response.msg || '获取信息失败');
        }
        // 更新工作经验
        commit('SET_WORK_EXPERIENCE', response.data.data);
        return response.data;
      } catch (error) {
        console.error('获取求职者工作经验失败:', error);
        // 发生错误时清除状态
        commit('CLEAR_STATE');
        throw error;
      }
    },

    // 更新工作经验的异步方法
    async renewWorkExperience({ commit }, workExperience) {
      try {
        // 先更新本地状态
        const data = workExperience;
        commit('SET_WORK_EXPERIENCE', data.workExperience);

        // 再发送到后端（JSON格式）
        const response = await updateWorkExperience(data.workExperience);
        const token = response.data.data;
        commit("SET_TOKEN", token);

        return response.data;
      } catch (error) {
        console.error('更新工作经验失败:', error);
        throw error;
      }
    },

    // 设置地址的异步方法
    async setAddress({ commit }, address) {
      try {
        // 先更新本地状态
        commit('SET_ADDRESS', address);
        return address;
      } catch (error) {
        console.error('设置地址失败:', error);
        throw error;
      }
    },

    //更新token
    async updateToken({ commit }, token) {
      commit('SET_TOKEN', token);
    },

    // 退出登录方法
    logout({ commit }) {
      commit('CLEAR_STATE');
      router.push('/login').then(() => {
        Message.success('退出登录成功，已跳转至登录页');
      }).catch(err => {
        // 处理跳转错误（例如重复跳转）
        Message.error('退出登录失败');

      });
    }
  },
  getters:{
    getUserInfo: state => state.userInfo
  }
}